package org.cheetah.core.action.spi;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.cheetah.core.action.Action;
import org.cheetah.core.action.ActionContext;
import org.cheetah.core.action.ActionDefinition;
import org.cheetah.core.exchange.Exchange;
import org.cheetah.core.language.CompiledExpression;

@XmlRootElement(name = "filter")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class FilterDefinition extends ActionDefinition {

	@XmlElement(name = "condition", required = true)
	private ExpressionDefinition expression;

	public FilterDefinition() {
		this.expression = null;
	}

	public FilterDefinition condition(ExpressionDefinition expression) {
		this.expression = expression;
		return this;
	}

	public Action createAction() throws Exception {
		return new ActionImpl(expression.compile());
	}

	private static class ActionImpl implements Action {
		private CompiledExpression condition;

		ActionImpl(CompiledExpression condition) {
			this.condition = condition;
		}

		public void process(ActionContext ctx, Exchange exchange)
				throws Exception {
			if (boolean.class.cast(condition.eval(exchange, boolean.class))) {
				ctx.process(exchange);
			}
		}
	}
}
